package com.hxh.wechat.activity

import android.app.AlertDialog
import android.content.*
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.hxh.wechat.util.ActivityCollector


open class BaseActivity : AppCompatActivity() {

    private var receiver: ForceOfflineReceiver? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 在创建 BaseActivity 时注册广播接收器
        val filter = IntentFilter()
        filter.addAction("com.hxh.wechat.FORCE_OFFLINE")
        receiver = ForceOfflineReceiver()
        registerReceiver(receiver, filter)
        ActivityCollector.addActivity(this);
    }

    override fun onDestroy() {
        super.onDestroy()
        // 在销毁 BaseActivity 时注销广播接收器
        unregisterReceiver(receiver)
    }

    internal class ForceOfflineReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent?) {
            val builder: AlertDialog.Builder = AlertDialog.Builder(context)
            builder.setTitle("警告")
            builder.setMessage("您的账号已在其他设备登录，请重新登录。")
            builder.setCancelable(false)
            builder.setPositiveButton("确定",
                DialogInterface.OnClickListener { dialog, which ->
                    ActivityCollector.finishAll() // 销毁所有活动
                    val intent = Intent(context, Login::class.java)
                    context.startActivity(intent) // 重新启动 LoginActivity
                })
            builder.show()
        }
    }
}